package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.pojo.OrderDetail;
import com.itheima.reggie.pojo.Orders;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrdersService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("order")
public class OrdersController {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private OrderDetailService orderDetailService;

    @PostMapping("submit")
    public R<String> submit(@RequestBody Orders orders){
        ordersService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 手机端订单信息详情
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("userPage")
    public R userPage(Integer page,Integer pageSize){
        //查询订单分页信息
        Page<Orders> pageInfo1 = new Page<>(page,pageSize);
        //分页条件
        LambdaQueryWrapper<Orders> wrapper1 = Wrappers.lambdaQuery(Orders.class)
                .orderByDesc(Orders::getOrderTime)
                .eq(Orders::getUserId, BaseContext.getCurrentId());
        ordersService.page(pageInfo1, wrapper1);
        Page<OrdersDto> pageInfo2= new Page<>(page,pageSize);
        //将分页数据转移到订单dto里
        BeanUtils.copyProperties(pageInfo1,pageInfo2,"records");
        ArrayList<OrdersDto> ordersDtoList = new ArrayList<>();
        for (Orders orders : pageInfo1.getRecords()) {
            OrdersDto ordersDto = new OrdersDto();
            BeanUtils.copyProperties(orders,ordersDto);
            LambdaQueryWrapper<OrderDetail> wrapper2 = Wrappers
                    .lambdaQuery(OrderDetail.class)
                    .eq(OrderDetail::getOrderId,orders.getId());
            List<OrderDetail> list = orderDetailService.list(wrapper2);
            ordersDto.setOrderDetails(list);
            ordersDtoList.add(ordersDto);
         }
        pageInfo2.setRecords(ordersDtoList);
        return R.success(pageInfo2);
    }

    /**
     * pc后台端订单信息详情
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("page")
    public R page(Integer page,Integer pageSize){
        Page<Orders> pageInfo = new Page<>(page,pageSize);
        LambdaQueryWrapper<Orders> wrapper = Wrappers.lambdaQuery(Orders.class)
                .orderByDesc(Orders::getOrderTime)
                .eq(Orders::getUserId, BaseContext.getCurrentId());
        ordersService.page(pageInfo, wrapper);
        return R.success(pageInfo);
    }
}


